package com.happypets.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class DogsFilter
 */
public class DogsFilter implements Filter {

    /**
     * Default constructor. 
     */
    public DogsFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		System.out.println("------dogsFilter start");
		
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		
		HttpSession session = req.getSession();
		
		String flag = (String)session.getAttribute("dogsFlag");
		String path = req.getContextPath();
		String kind = request.getParameter("kind");
		String color = request.getParameter("color");
		String shape = request.getParameter("shape");
		String category = request.getParameter("category");
		String keywords = request.getParameter("keywords");
		
		System.out.println("shape = "+shape+"color = "+color+"a.category = "+category+" keywords = "+keywords);
		
		System.out.println("dogsFilter flag = "+flag);
		
		System.out.println("kind = "+kind);
		
		if(kind == null){
			kind = "1";
		}
		
		//搜索时新增keywords
		
		if(shape != null || color != null || category != null || keywords != null){
			System.out.println(path+"/SearchServlet?shape="+shape+"&color="+color+"&category="+category+"&kind="+kind+"&keywords="+keywords);
			
			session.setAttribute("shape", shape);
			session.setAttribute("category", category);
			session.setAttribute("color", color);
			session.setAttribute("keywords", keywords);
			
			resp.sendRedirect(path+"/SearchServlet?kind="+kind);
//			resp.sendRedirect(path+"/SearchServlet?shape="+shape+"&color="+color+"&category="+category+"&kind="+kind+"&keywords="+keywords);
		}else{
			if(flag != null){
				chain.doFilter(request, response);
			}else{
				resp.sendRedirect(path+"/DogsServlet?kind="+kind);
			}
		}
		
		
		
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
